﻿using UnityEngine;
using System.Collections;

public class Inventory : MonoBehaviour
{
	public Slot[] slotList;

    /// <summary>
    /// 控制面板的透明度从而控制显示或隐藏
    /// </summary>
    private float targetAlpha=1;
    private CanvasGroup cg;
    private float lerpSpeed=2.0f;

	protected virtual void Start()
	{
		slotList = this.GetComponentsInChildren<Slot>();
        cg = this.GetComponent<CanvasGroup>();
	}

    void Update()
    {
        if (targetAlpha != this.cg.alpha)
        {
            this.cg.alpha = Mathf.Lerp(this.cg.alpha, targetAlpha, lerpSpeed * Time.deltaTime);
            if (Mathf.Abs(this.cg.alpha - targetAlpha) <= 0.01f)
            {
                this.cg.alpha = targetAlpha;
            }
        }
    }

	public bool StoreGood(int ID)
	{
		KnapsackGood good = KnapsackManager.GetInstance.GetGoodWithID(ID);
		return StoreGood(good);
	}


	public bool StoreGood(KnapsackGood good)
	{
		if (good == null)
		{
			Debug.Log("需要存储的物品为空");
			return false;
		}
		if (good.goodProperty.capacity == 1)//如果该物品在物品槽中只能存放一个
		{//直接找到一个还没有使用的物品槽
			Slot slot = FindEmptySlot();
			if (slot != null)//如果找到了空的物品槽，那么将该物品发进去
			{
				slot.StoreGood(good);
			}
			else//如果没有找到，则将说明背包以满
			{
				Debug.Log("没有找到空的物品槽，可能是背包以满");
				return false;
			}
		}
		else
		{//先寻找是否已经有存放了该物品的物品槽
			Slot slot = FindFreeSlot(good.goodProperty.ID);
			if (slot != null)
			{
				slot.StoreGood(good);
			}
			else
			{
				Slot s = FindEmptySlot();
				if (s != null)
				{
					s.StoreGood(good);
				}
				else
				{
					Debug.Log("没有找到空的物品槽，可能是背包以满");
					return false;
				}
			}
		}
		return true; ;
	}

	/// <summary>
	/// 根据ID寻找存储了该物品的物品槽
	/// </summary>
	/// <returns></returns>
	private Slot FindFreeSlot(int ID)
	{
		foreach (Slot s in slotList)
		{
			if (s.transform.childCount > 0 && s.GetGoodID() == ID&&s.IsFill()==false)
			{
				return s;
			}
		}

		return null;
	}


	private Slot FindEmptySlot()
	{
		foreach (Slot s in slotList)
		{
			//还没有存放物品的物品槽中也没有添加GoodUI,根据该物品槽中是否有子节点这个线索来判断是否存放物品
			if (s.transform.childCount == 0||s.transform.gameObject.activeInHierarchy==false)
			{
				return s;
			}
		}

		//没有找到空的物品槽，说明背包以满
		return null;
	}


    public void ShowPanel()
    {
        targetAlpha = 1;
        this.cg.blocksRaycasts = true;
    }


    public void HidePanel()
    {
        targetAlpha = 0;
        this.cg.blocksRaycasts = false;
    }
}
